package org.onion.pattern.kit.validation.annotation.validator;


import org.onion.pattern.kit.validation.annotation.Within;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.apache.commons.lang3.ArrayUtils;

/**
 * 元素验证
 *
 */
public class ElementsValidator implements ConstraintValidator<Within, Object> {

    private String[] values;
    private String[] strings;
    private char[]   chars;
    private double[] doubles;
    private float[]  floats;
    private int[]    ints;
    private long[]   longs;
    private short[]  shorts;

    @Override
    public void initialize(Within constraintAnnotation) {
        values = constraintAnnotation.value();
        strings = constraintAnnotation.strEle();
        chars = constraintAnnotation.charEle();
        doubles = constraintAnnotation.doubleEle();
        floats = constraintAnnotation.floatEle();
        ints = constraintAnnotation.intEle();
        longs = constraintAnnotation.longEle();
        shorts = constraintAnnotation.shortEle();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }

        if (value instanceof String) {
            return ArrayUtils.contains(values, value) || ArrayUtils.contains(strings, value);
        }

        if (value instanceof Integer) {
            return ArrayUtils.contains(ints, (Integer) value);
        }

        if (value instanceof Long) {
            return ArrayUtils.contains(longs, (Long) value);
        }

        if (value instanceof Double) {
            return ArrayUtils.contains(doubles, (Double) value);
        }

        if (value instanceof Float) {
            return ArrayUtils.contains(floats, (Float) value);
        }

        if (value instanceof Short) {
            return ArrayUtils.contains(shorts, (Short) value);
        }

        if (value instanceof Character) {
            return ArrayUtils.contains(chars, (Character) value);
        }

        throw new IllegalStateException("无法验证类型：" + value.getClass());

    }

}
